<?php
/**
 * 库存管理模型 
 * @author wolf5x
 */
class m_stockback extends base_m {
	public function primarykey() {
		return 'stockback_id';
	}
	public function tableName() {
		return base_Constant::TABLE_PREFIX . 'stockback';
	}
	public function relations() {
		return array ();
	}
	
	public function create($data, $upd = true) {
		if(!$data['goods_id']) {
			$this->setError(0, '商品编号不能为空');
			return false;
		}
		$goodsObj = base_mAPI::get ( 'm_goods', $data['goods_id'] );
		$rs = $goodsObj->get();
		if( $upd && !$rs) {
			$this->setError(0, '商品信息不存在');
			return false;
		}

		if( $rs['goods_id'] != $data['goods_id']
			|| $rs['goods_sn'] != $data['goods_sn']
			|| $rs['goods_name_chn'] != $data['goods_name_chn']
			|| $rs['goods_name_tha'] != $data['goods_name_tha']
		) {
			$this->setError(0, "商品数据异常!");
			return false;
		}

		$goods_pack_num = (int)$data['goods_pack_num'];
		if( $goods_pack_num <= 0 
			|| $goods_pack_num != intval($goods_pack_num)) {
			$this->setError(0, "退货数量必须为大于0的整数！");
			return false;
		}

		$stockback_opttime = date('YmdHis');
		$date_start = date('Y-m-d');
	
		// TODO
		$outDet = base_mAPI::get( 'm_stockoutdetail' );
		$sum_today = $outDet->packNumByCondition(
			array(
				'goods_sn' => $rs['goods_sn'],
				'goods_name_chn' => $rs['goods_name_chn'],
				'goods_name_tha' => $rs['goods_name_tha'],
				'date_start' => $date_start
			)
		);
		if($sum_today === false){
			$this->setError(0, "统计今日出库总量失败：" . $outDet->getError());
			return false;
		}

		if( $goods_pack_num > $sum_today) {
			$this->setError(0, "退货量({$goods_pack_num})不能大于今日出库总量({$sum_today})！");
			return false;
		}

		//$content = $data ['content'] ? $data ['content'] : "增加入库：名称：{$rs ['goods_name']},数量：{$data ['in_num']}";
		$this->set ( "goods_sn", $data ['goods_sn'] );
		$this->set ( "goods_name_chn", $data ['goods_name_chn'] );
		$this->set ( "goods_name_tha", $data ['goods_name_tha'] );
		$this->set ( "goods_pack_num", $goods_pack_num );
		$this->set ( "stockback_opttime", $stockback_opttime);
		$stockback_id = $res = $this->save(false);
		if($res){
			if($upd){
				$res = $goodsObj->setStock ( $rs['goods_id'], $goods_pack_num, 1 ); //更新库存
			}
			if($res){
				return true;
			}
			$this->set('isdel',1);
			$this->save();
			$this->setError ( 0, "更新商品库存失败:" . $goodsObj->getError () );
			return false;
		}
		$this->setError( 0, "写入退货数据失败:" . $this->getError() );
		return false;
	}

}
